<!DOCTYPE html>
<html lang="zh-CN">
{% load static %}
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>按天统计发票报表</title>
    <!-- 引用本地static目录下的CSS文件 -->
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/bootstrap-icons.css' %}">
    <!-- 引用本地static目录下的JS文件 -->
    <script src="{% static 'js/vue.global.js' %}"></script>
    <script src="{% static 'js/axios.min.js' %}"></script>
    <!-- 引用ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
</head>
{% verbatim %}
<body>

<div id="app" class="container-fluid py-4">
    <div class="row">
        <!-- 标题和查询区域 -->
        <div class="col-12">
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-bar-chart-line-fill"></i> 按天统计发票报表
                    </h5>
                </div>
                <div class="card-body">
                    <form class="row g-3 align-items-center">
                        <div class="col-auto">
                            <label class="col-form-label">查询年月：</label>
                        </div>
                        <div class="col-auto">
                            <input type="month" 
                                   class="form-control" 
                                   v-model="searchForm.year_month" 
                                   placeholder="请选择年月">
                        </div>
                        <div class="col-auto">
                            <button type="button" 
                                    class="btn btn-primary" 
                                    @click="loadData">
                                <i class="bi bi-search"></i> 查询
                            </button>
                            <button type="button" 
                                    class="btn btn-secondary ms-2" 
                                    @click="resetSearch">
                                <i class="bi bi-arrow-clockwise"></i> 重置
                            </button>
                        </div>
                        <div class="col-auto ms-auto">
                            <span class="badge bg-info text-dark">当前查询月份：{{ searchForm.year_month }}</span>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- ECharts图表区域 -->
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-light">
                    <h6 class="mb-0">
                        <i class="bi bi-graph-up"></i> 发票金额按天统计趋势图
                    </h6>
                </div>
                <div class="card-body">
                    <!-- 加载提示 -->
                    <div v-if="loading" class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2 text-muted">数据加载中，请稍候...</p>
                    </div>
                    <!-- 图表容器 -->
                    <div id="chartContainer" 
                         v-show="!loading" 
                         style="width: 100%; height: 500px;">
                    </div>
                    <!-- 无数据提示 -->
                    <div v-if="!loading && chartData.days.length === 0" 
                         class="text-center py-5 text-muted">
                        <i class="bi bi-inbox" style="font-size: 3rem;"></i>
                        <p class="mt-3">暂无数据</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
const { createApp } = Vue;

createApp({
    data() {
        return {
            // 搜索表单
            searchForm: {
                year_month: this.getCurrentYearMonth()
            },
            // 加载状态
            loading: false,
            // 图表实例
            chartInstance: null,
            // 图表数据
            chartData: {
                days: [],
                totalAmount: [],
                totalTax: [],
                totalPriceTax: []
            }
        };
    },
    mounted() {
        // 页面加载时初始化图表并加载数据
        this.initChart();
        this.loadData();
    },
    methods: {
        // 获取当前年月（格式：YYYY-MM）
        getCurrentYearMonth() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            return `${year}-${month}`;
        },
        
        // 初始化ECharts图表
        initChart() {
            const chartDom = document.getElementById('chartContainer');
            this.chartInstance = echarts.init(chartDom);
            
            // 设置初始配置
            const option = {
                title: {
                    text: '发票金额按天统计',
                    left: 'center',
                    top: 10
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    },
                    formatter: function(params) {
                        let result = `<strong>日期：${params[0].axisValue}号</strong><br/>`;
                        params.forEach(item => {
                            result += `${item.marker} ${item.seriesName}：¥${item.value.toLocaleString()}<br/>`;
                        });
                        return result;
                    }
                },
                legend: {
                    data: ['合计金额(不含税)', '合计税额', '价税合计'],
                    top: 40
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    top: 80,
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: [],
                    name: '天',
                    nameLocation: 'end',
                    axisLabel: {
                        formatter: '{value}号'
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '金额（元）',
                    axisLabel: {
                        formatter: function(value) {
                            if (value >= 10000) {
                                return (value / 10000).toFixed(1) + '万';
                            }
                            return value.toLocaleString();
                        }
                    }
                },
                series: [
                    {
                        name: '合计金额(不含税)',
                        type: 'line',
                        smooth: true,
                        data: [],
                        itemStyle: {
                            color: '#5470c6'
                        },
                        lineStyle: {
                            width: 2
                        }
                    },
                    {
                        name: '合计税额',
                        type: 'line',
                        smooth: true,
                        data: [],
                        itemStyle: {
                            color: '#fac858'
                        },
                        lineStyle: {
                            width: 2
                        }
                    },
                    {
                        name: '价税合计',
                        type: 'line',
                        smooth: true,
                        data: [],
                        itemStyle: {
                            color: '#ee6666'
                        },
                        lineStyle: {
                            width: 2
                        }
                    }
                ]
            };
            
            this.chartInstance.setOption(option);
            
            // 响应式调整
            window.addEventListener('resize', () => {
                this.chartInstance.resize();
            });
        },
        
        // 更新图表数据
        updateChart() {
            if (!this.chartInstance) return;
            
            const option = {
                xAxis: {
                    data: this.chartData.days
                },
                series: [
                    {
                        data: this.chartData.totalAmount
                    },
                    {
                        data: this.chartData.totalTax
                    },
                    {
                        data: this.chartData.totalPriceTax
                    }
                ]
            };
            
            this.chartInstance.setOption(option);
        },
        
        // 加载数据
        loadData() {
            console.log('开始加载数据，查询年月：', this.searchForm.year_month);
            this.loading = true;
            
            axios.get('/invoice/data_day_statistics', {
                params: {
                    year_month: this.searchForm.year_month
                }
            })
            .then(response => {
                console.log('API响应数据：', response.data);
                const data = response.data;
                
                // 兼容多种响应格式
                if (data.status === 'success' || data.code === 200 || response.status === 200) {
                    const statistics = data.data?.statistics || [];
                    console.log('统计数据：', statistics);
                    
                    // 提取数据
                    this.chartData.days = statistics.map(item => item.day);
                    this.chartData.totalAmount = statistics.map(item => item.total_amount);
                    this.chartData.totalTax = statistics.map(item => item.total_tax);
                    this.chartData.totalPriceTax = statistics.map(item => item.total_price_tax);
                    
                    console.log('图表数据已更新：', this.chartData);
                    
                    // 更新图表
                    this.updateChart();
                } else {
                    const message = data.message || data.msg || '数据加载失败';
                    console.error('加载失败：', message);
                    alert('数据加载失败：' + message);
                }
            })
            .catch(error => {
                console.error('请求失败：', error);
                alert('请求失败，请检查网络连接');
            })
            .finally(() => {
                this.loading = false;
            });
        },
        
        // 重置搜索
        resetSearch() {
            this.searchForm.year_month = this.getCurrentYearMonth();
            this.loadData();
        }
    }
}).mount('#app');
</script>

</body>
{% endverbatim %}
</html>